package com.jiangjiang.eshop.commodity.operation;

import com.jiangjiang.eshop.commodity.dto.CategoryDTO;
import com.jiangjiang.eshop.commodity.service.CategoryService;

import java.util.List;

/**
 * @ClassName AbstractCategoryOperation
 * @Description TODO
 * @Author jhw
 * @Date 2021/7/9 14:40
 * @Version 1.0
 **/
public abstract class AbstractCategoryOperation<T> implements CategoryOperation<T> {

    protected CategoryService categoryService;

    public AbstractCategoryOperation(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @Override
    public T doExecute(Category category) throws Exception {
        doExecuteForChildren(category);
        return doRealExecute(category);
    }


    /**
     *  执行实际操作
     * @param category 类目节点
     * @return 处理结果
     * @throws Exception 异常
     */
    protected abstract T doRealExecute(Category category) throws Exception;


    /**
     * 递归对当前的子类进行处理
     *
     * @param category 当前类目节点
     * @throws Exception
     */
    private void doExecuteForChildren(Category category) throws Exception {
        List<CategoryDTO> children = categoryService.listChildren(category.getCategoryId());
        for (CategoryDTO child : children) {
            Category childCategory = new Category(child.getId());
            childCategory.execute(this);
        }
    }
}
